let HOST = window.location.origin;

function init() {
    //回车事件绑定
    $('#userIDInput').bind('keyup', function (event) {
        if (event.keyCode == "13") {
            //回车执行查询
            search()
        }
    });


    var clipboard = new ClipboardJS('.sf-btn');
    clipboard.on('success', function (e) {
        // console.info('Action:', e.action);
        // console.info('Text:', e.text);
        // console.info('Trigger:', e.trigger);

        layer.msg(`复制成功：${e.text}`)

        e.clearSelection();
    });

    clipboard.on('error', function (e) {
        layer.msg(`复制失败：${e.action}`)
    });


}

$(function () {

    init();

})

function replaceNum(obj) {
    let text = $(obj).text();

    $("#userIDInput").val(text.trim())

    search()

}


function search() {
    $("#dataBody").html('')
    $("#dataBodyForSTB").html('')


    let userID = $("#userIDInput").val();

    if (!userID) {
        layer.msg('必须输入ITV号码');
        return
    }


    if (userID.startsWith("0")) {
        userID = userID.substring(4);
    }

    getDataByUserID(userID);

    getDataByUserIDForSTB(userID);

}

/**
 * 获取用户订购信息  来自机顶盒页面 包含退订过的
 * @param userID
 */
function getDataByUserIDForSTB(userID) {
    let url = HOST + "/sdbysfuser/getOrdersByUserIDForSTB";

    $.get(url, {"userID": userID}, function (res) {
        if (200 !== res.code) {
            layer.msg("出错了:" + res.messsage)
            return
        }


        parserOrderInfosDataForSTB(userID, res.result);

    })

}


/**
 * 解析来自机顶盒上的数据
 * @param userID
 * @param res
 */
function parserOrderInfosDataForSTB(userID, res) {
    let trHtml = ''
    let index = 0;
    for (let i in res) {
        let item = res[i];

        index++;

        let startTime = formatDateTime(item.startTime)
        let endTime = formatDateTime(item.endTime)


        let type = item.type

        trHtml += `
                     <tr>
                        <td>${index}</td>
                        <td>${userID}</td>
                        <td>${item.productID}</td>
                        <td>${item.productName}</td>
                        <td>${startTime}</td>
                        <td>${endTime}</td>
                        <td>${type}</td>
                        <td>${item.fee}</td>
                    </tr>
                `

    }
    $("#dataBodyForSTB").html('')
    $("#dataBodyForSTB").html(trHtml)
}


/**
 * 获取用户订购信息
 * @param userID
 */
function getDataByUserID(userID) {
    let url = HOST + "/sdbysfuser/getOrdersByUserID";

    $.get(url, {"userID": userID}, function (res) {
        if (200 !== res.code) {
            layer.msg("出错了:" + res.messsage)
            return
        }

        if (res.result.result !== '0') {
            layer.msg("出错了:" + res.result.result)
            return
        }

        let orderInfo = res.result.orderInfo;

        parserOrderInfosData(userID, orderInfo);

    })

}

/**
 * 解析用户订购关系
 */
function parserOrderInfosData(userID, orderInfo) {
    let trHtml = ''

    if (!orderInfo || orderInfo.length === 0) {
        trHtml = '<tr><td colspan="15">暂无数据</td></tr>'
    }


    let index = 0;
    for (let i in orderInfo) {

        let item = orderInfo[i];

        index++;

        let orderType = item.orderType

        orderType = parserOrderType(orderType)


        // 订购生效时间yyyyMMddHHmmss

        let subscribeTime = item.subscribeTime;
        let effectiveTime = item.effectiveTime;
        let unsubscribeTime = item.unsubscribeTime;
        let expiredTime = item.expiredTime;


        //20200902182454
        //2099
        let syncGdParam = ''

        if (expiredTime.startsWith("2099")) {
            syncGdParam += '1#'
        } else {
            syncGdParam += '0#'
        }

        let productID = item.productID;

        syncGdParam += `${userID.trim()}#${subscribeTime}#${expiredTime}##${productID}#1`


        if (subscribeTime) {
            subscribeTime = formatDateTime(subscribeTime);
        } else {
            subscribeTime = '/'
        }


        if (effectiveTime) {
            effectiveTime = formatDateTime(effectiveTime);
        } else {
            effectiveTime = '/'
        }


        if (unsubscribeTime) {
            unsubscribeTime = formatDateTime(unsubscribeTime);
        } else {
            unsubscribeTime = '/'
        }


        if (expiredTime) {
            expiredTime = formatDateTime(expiredTime);

        } else {
            expiredTime = '/'
        }

        let orderChannel = item.orderChannel;
        if (orderChannel === '1') {
            orderChannel = 'EPG'
        } else {
            orderChannel = 'CRM'
        }


        trHtml += `
                     <tr>
                        <td>${index}</td>
                        <td>${userID}</td>
                        <td>${productID}</td>
                        <td>${item.productName}</td>
                        <td>${subscribeTime}</td>
                        <td>${effectiveTime}</td>
                        <td class="layui-hide">${unsubscribeTime}</td>
                        <td >${expiredTime}</td>
                        <td>${orderType}</td>
                        <td>${orderChannel}</td>
                        <td>${item.productPrice}</td>
                        <td>
                            <button type="button" data-clipboard-text='${syncGdParam}'   title="同步广电" class="layui-btn-warm layui-btn sf-btn">复制参数</button>
                            <button type="button" onclick="unsubscribe('${userID}','${productID}','1')"  title="退订操作，谨慎操作！" class="layui-btn layui-btn">退订</button>
                            <button type="button"  onclick="unsubscribe('${userID}','${productID}','0')"   title="退订操作，谨慎操作！" class="layui-btn layui-btn-danger">立即失效</button>
                        </td>
                    </tr>
                `

    }
    $("#dataBody").html('')
    $("#dataBody").html(trHtml)

}

/**
 * 解析转换订购方式
 * @param orderType
 */
function parserOrderType(orderType) {

    switch (parseInt(orderType)) {
        case 3:
            orderType = '话单';
            break;
        case 5:
            orderType = '积分';
            break;
        case 8:
            orderType = 'crm';
            break;
        case 9:
            orderType = '微信';
            break;
        case 11:
            orderType = '翼支付';
            break;
        case 12:
            orderType = '支付宝';
            break;
        case 13:
            orderType = '兑换券';
            break;

    }

    return orderType
}

/**
 * 解析日期时间
 * @param date
 */
function formatDateTime(date) {
    return date.substring(0, 4)
        + "-" + date.substring(4, 6)
        + "-" + date.substring(6, 8)
        + " " + date.substring(8, 10)
        + ":" + date.substring(10, 12)
        + ":" + date.substring(12, 14)

}

/**
 * 退订
 * @param userId
 * @param productID
 * @param action
 */
function unsubscribe(userID, productID, action) {

    //询问框
    let confirmLayer = layer.confirm(`你正在操作${action === '0' ? '立即失效' : '取消续订'}【${productID}】？`, {
        btn: ['确认', '取消'] //按钮
    }, function () {

        let url = HOST + "/sdbysfuser/OrderUnsubscribe";

        $.post(url, {"userID": userID, "productID": productID, "action": action}, function (res) {
            if (200 !== res.code) {
                layer.msg("出错了:" + res.messsage)
                return
            }

            if (res.result.result !== '0') {
                layer.msg("出错了:" + res.result.description)
                return
            }

            layer.msg("操作成功")

            search()

        })

    }, function () {
        layer.close(confirmLayer)
        layer.msg("取消操作！")
    });


}

